package cn.edu.zut.response;

import cn.edu.zut.mapper.UserMapper;
import cn.edu.zut.pojo.User;
import cn.edu.zut.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author Davey chan
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//结束用户名和密码
        String username=request.getParameter("username");
        String password=request.getParameter("password");
//        调用Mybatis完成查询
//        获取SQLsessionFactory对象
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//        获取sqlsesion对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
//      获取mapper对象
        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
//        调用方法
        User user= usermapper.select(username, password);

//        释放资源
        sqlSession.close();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer=response.getWriter();

//        判断user是否为null
        if(user!=null){
            writer.write("登录成功");
        }else{
            writer.write("登录失败");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
